package com.qqtech.qquan.vote.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.vote.model.VoteBaseVo;
import com.qqtech.qquan.vote.model.VoteItem;
import com.qqtech.qquan.vote.model.VoteItemQuery;
import com.qqtech.qquan.vote.model.VoteItemVo;
import com.qqtech.qquan.vote.service.VoteBaseService;
import com.qqtech.qquan.vote.service.VoteItemService;
import com.qqtech.qquan.vote.service.VoteResultService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/vote/item")
public class VoteItemController extends BaseWebController<VoteItem, VoteItemQuery> {
	@Resource
	private VoteItemService voteItemService;

	@Resource
	private VoteResultService voteResultService;

	@Resource
	private VoteBaseService voteBaseService;

	@Override
	protected BaseService<VoteItem> getBaseService() {
		return voteItemService;
	}

	/**
	 * 列表
	 * 
	 * @param voteItemQuery
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Result list(@RequestBody VoteItemQuery voteItemQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		VoteBaseVo voteBaseVo = voteBaseService.getById(voteItemQuery.getVoteId());
		List<VoteItemVo> list = voteItemService.queryList(voteItemQuery);
		boolean isResult = true;
		if (null != curUserId) {
			isResult = voteResultService.isResult(voteItemQuery.getVoteId(), curUserId);
		}
		int totalResult = voteResultService.getTotalVoteResult(voteItemQuery.getVoteId());
		if(totalResult>0){
			Integer voteItemResult;
			for (VoteItemVo voteItemVo : list) {
				voteItemResult = voteResultService.getVoteItemResult(voteItemQuery.getVoteId(), voteItemVo.getId());
				voteItemVo.setPercent(voteItemResult);
			}
		}else{
			for (VoteItemVo voteItemVo : list) {
				voteItemVo.setPercent(null);
			}
		}
		result.put("isResult", isResult);
		result.put("voteBaseVo", voteBaseVo);
		result.put("list", list);
		return result;
	}

	/**
	 * 新增
	 * 
	 * @param voteBaseVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create")
	@ResponseBody
	public Result create(@RequestBody VoteItemVo voteItemVo) {
		Result result = new Result();
		voteItemService.insert(voteItemVo);
		return result;
	}
}
